/*
 * Created on Feb 14, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell;

import it.okkam.longwell.locale.Localize;
import it.okkam.longwell.ui.command.AdministrationAccessesCommand;
import it.okkam.longwell.ui.command.AdministrationCommand;
import it.okkam.longwell.ui.command.AdministrationDatasetsCommand;
import it.okkam.longwell.ui.command.AdministrationUsersCommand;
import it.okkam.longwell.ui.command.BrowseDefaultModelCommand;
import it.okkam.longwell.ui.command.ChangeModelCommand;
import it.okkam.longwell.ui.command.CreateCertificateCommand;
import it.okkam.longwell.ui.command.DisableAdminCommand;
import it.okkam.longwell.ui.command.DisableUsersCommand;
import it.okkam.longwell.ui.command.DomandeCompetenzaCommand;
import it.okkam.longwell.ui.command.EnableUsersCommand;
import it.okkam.longwell.ui.command.EnableUsersToAdminCommand;
import it.okkam.longwell.ui.command.GetSourceCommand;
import it.okkam.longwell.ui.command.GraphsListAdministrationCommand;
import it.okkam.longwell.ui.command.HomePageCommand;
import it.okkam.longwell.ui.command.LoadServerCertificateCommand;
import it.okkam.longwell.ui.command.LoginBasicCommand;
import it.okkam.longwell.ui.command.LoginBasicAdministrationCommand;
import it.okkam.longwell.ui.command.LoginWebidCommand;
import it.okkam.longwell.ui.command.LogoutCommand;
import it.okkam.longwell.ui.command.PrintCommand;
import it.okkam.longwell.ui.command.QuestionsListCommand;
import it.okkam.longwell.ui.command.SaveCertificateCommand;
import it.okkam.longwell.ui.command.SaveUserBasicCommand;
import it.okkam.longwell.ui.command.SaveUserWebidCommand;
import it.okkam.longwell.ui.command.SelectDatasetAdministrationCommand;
import it.okkam.longwell.ui.command.SelectDatasetCommand;
import it.okkam.longwell.ui.command.SelectLoadingTypeCommand;
import it.okkam.longwell.ui.command.SetDatasetCommand;
import it.okkam.longwell.ui.command.SelectGraphsCommand;
import it.okkam.longwell.ui.command.UserRegistrationCommand;
import it.okkam.longwell.ui.command.UserRegistrationBasicCommand;
import it.okkam.longwell.ui.command.UserRegistrationWebidCommand;
import it.okkam.webid.model.DataModel;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.mortbay.http.ResourceCache;
import org.mortbay.util.Resource;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.util.FileManager;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.corpus.Corpus;
import edu.mit.simile.longwell.query.Query;
import edu.mit.simile.longwell.renderer.MapMarkerRenderer;
import edu.mit.simile.longwell.renderer.Renderer;
import edu.mit.simile.longwell.ui.FlairLocalProfile;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.BrowseCommand;
import edu.mit.simile.longwell.ui.command.ExportCommand;
import edu.mit.simile.longwell.ui.command.FocusCommand;
import edu.mit.simile.longwell.ui.command.IFlairCommand;
import edu.mit.simile.longwell.ui.command.StartCommand;
import edu.mit.simile.longwell.ui.command.ViewCommand;

/**
 * @author dfhuynh
 */
public class LongwellServlet extends HttpServlet {
    final static private Logger s_logger = Logger.getLogger(LongwellServlet.class);
    protected VelocityEngine 	m_ve;
    protected Map 				m_getCommands = new HashMap();
    protected Map 				m_postCommands = new HashMap();
    protected ResourceCache		m_resourceCache;
    protected ServletContext 	m_context;
	protected boolean login = LoginBasicCommand.userInput;
	protected String l= new Boolean(login).toString();
	private Corpus m_corpus;
	public static ArrayList<Dataset> m_dataset;
	static private File m_TDBAssembler;
	private Profile m_profile;
	private Properties m_properties;
	private LongwellServer longwellServer = null;
	private File[] filesComuni;
	String sessionId;
	private  Corpus corpus = null;
	private PropertyResourceBundle languageBundle = null;
	String language="";
	private Model modelForAuthentication = null;
    /* (non-Javadoc)
     * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
    
	public ArrayList<Dataset> getDataset(){
		return m_dataset;
	}
    /* (non-Javadoc)
     * @see javax.servlet.GenericServlet#destroy()
     */
    public void destroy() {
        try {
            m_resourceCache.stop();
            m_resourceCache = null;
        } catch (InterruptedException e) {
            s_logger.error("Failed to stop resource cache", e);
        }

        super.destroy();
    }
    
    Pattern marker_pattern = Pattern.compile("^/resources/marker$");
    Renderer markerRenderer = new MapMarkerRenderer();
    
    
    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	HttpSession session = request.getSession(true);
    	sessionId = session.getId();
    	//s_logger.info("request doGet from session: "+sessionId);
        String pathInContext = request.getPathInfo();
        Matcher m = null;
        m = marker_pattern.matcher(pathInContext);
        if(LongwellServer.getServer()== null){
        	configureServer(sessionId);
        } 
        if(LongwellServer.getServer().getProfile(sessionId)==null){
        	configureServer(sessionId);
        }
        if (m.matches()) {
        	render(request, response, markerRenderer);
            if (s_logger.isDebugEnabled()) s_logger.debug("< doGet");
            return;
        }else if (pathInContext.startsWith("/resources/")) {
            serveResource(request, response);
        } else {
        	FlairMessage msg = makeMessage(request, response);          
            String command = msg.m_query.getFirstParamValue("command");
            if (command == null) {
            	session.setAttribute("graphName",null);
                //command = "start"; //command without login
            	//command = "login";
            	command = "home";
            }
            IFlairCommand flairCommand = (IFlairCommand) m_getCommands.get(command);
            if (command != null) {
                response.setContentType("text/html");
                flairCommand.execute(msg);
            } else {
                response.getOutputStream().println("No such command: " + command);
            }
        }
        
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	HttpSession session = request.getSession(true);
    	sessionId = session.getId();
    	//s_logger.info("request doPost from session: "+sessionId);
        if(LongwellServer.getServer()== null || LongwellServer.getServer().getProfile(sessionId)==null){
        	configureServer(sessionId);
        }    	
        FlairMessage msg = makeMessage(request, response);
        String command = msg.m_query.getFirstParamValue("command");
        s_logger.info("command = "+command);
        if (command == null) {
            command = "home";
            //command = "start";
        }

        IFlairCommand flairCommand = (IFlairCommand) m_postCommands.get(command);
        if (flairCommand != null) {
            response.setContentType("text/html");
            flairCommand.execute(msg);
        } else {
            response.getOutputStream().println("No such command: " + command);
        }
    }

    protected Properties createInitProperties(File flairDir) throws Exception {
        Properties properties = new Properties();      
        File flairServerSideDir = new File(flairDir, "server-side");

        // Templates
        properties.setProperty(
            RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
            flairServerSideDir.getAbsolutePath());
        System.out.println("flairServersSideDir "+flairServerSideDir.getAbsolutePath());
        // Macros
        File[] files = new File(flairServerSideDir, "macros").listFiles();
        String s = "";
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (!file.isHidden()) {
                String name = file.getName();
                if (name.endsWith(".vm") && !name.equals("login.vm")) {
                    s = s + (s.length() == 0 ? "" : ",") + "macros/" + name;
                }
            }
        }
        System.out.println(s);
        properties.setProperty("velocimacro.library", s);

        // Other properties
        FileInputStream fis = new FileInputStream(
            new File(flairServerSideDir, "velocity.properties"));

        properties.load(fis);
        fis.close();

        return properties;
    }

    protected void createCommands(ServletConfig config) {
        InjectionManager injections = createInjectionManager();
        m_getCommands.put("loginbasic", new LoginBasicCommand(injections,"templates/commands/login.vt"));
        m_getCommands.put("loginbasicAdministrator", new LoginBasicAdministrationCommand(injections,"templates/commands/loginAdministrator.vt"));
        m_getCommands.put("loginwebid", new LoginWebidCommand(injections,"templates/commands/home.vt"));
        m_getCommands.put("administration", new AdministrationCommand(injections,"templates/commands/administration.vt"));
        m_getCommands.put("administration_users", new AdministrationUsersCommand(injections,"templates/commands/administration_users.vt"));
        m_getCommands.put("administration_datasets", new AdministrationDatasetsCommand(injections,"templates/commands/administration_datasets.vt"));
        m_getCommands.put("administration_accesses", new AdministrationAccessesCommand(injections,"templates/commands/administration_accesses.vt"));
        m_getCommands.put("selectDatasetForAdministration", new SelectDatasetAdministrationCommand(injections,filesComuni, "templates/components/dataset-list-administration.vt"));
        
        m_getCommands.put("home", new HomePageCommand(injections,"templates/commands/home.vt"));
        m_getCommands.put("enableUsers", new EnableUsersCommand(injections));
        m_getCommands.put("fromUsersToAdministrator", new EnableUsersToAdminCommand(injections));  
        m_getCommands.put("fromUsersToPending", new DisableUsersCommand(injections));
        m_getCommands.put("disableAdmin", new DisableAdminCommand(injections));
        
        m_getCommands.put("user_registration", new UserRegistrationCommand(injections,"templates/commands/user_registration.vt"));
        m_getCommands.put("user_registration_basic", new UserRegistrationBasicCommand(injections,"templates/commands/user_registration_basic.vt"));
        m_getCommands.put("user_registration_webid", new UserRegistrationWebidCommand(injections,"templates/commands/user_registration_webid.vt"));

        m_getCommands.put("save_user_basic", new SaveUserBasicCommand(injections,"templates/commands/save_user_basic.vt"));   
        m_postCommands.put("save_user_basic", new SaveUserBasicCommand(injections,"templates/commands/save_user_basic.vt"));
        m_getCommands.put("save_user_webid", new SaveUserWebidCommand(injections,"templates/commands/save_user_webid.vt"));        

        m_postCommands.put("graphsListAdministration", new GraphsListAdministrationCommand(injections,"templates/components/graphs-list-administration.vt"));
        
        m_getCommands.put("start", new StartCommand(injections,filesComuni, "templates/commands/start.vt"));
        m_getCommands.put("selectGrafi", new SelectGraphsCommand(injections,"templates/components/graphs-list.vt"));
        m_getCommands.put("graphsListAdministration", new GraphsListAdministrationCommand(injections,"templates/components/graphs-list-administration.vt"));
        
        m_getCommands.put("changeModel", new ChangeModelCommand(injections,m_corpus,m_dataset,m_profile, "templates/commands/start.vt"));
        m_getCommands.put("questions_list", new QuestionsListCommand(injections,"templates/commands/questions-list.vt"));
        m_getCommands.put("domanda", new DomandeCompetenzaCommand(injections));
        
        m_getCommands.put("create_certificate", new CreateCertificateCommand(injections,"templates/commands/create_certificate.vt"));
        m_getCommands.put("save_certificate", new SaveCertificateCommand(injections,"templates/commands/create_certificate.vt"));
        
        m_getCommands.put("load_server_certificate", new LoadServerCertificateCommand(injections));
        m_getCommands.put("selectLoadingType", new SelectLoadingTypeCommand(injections,"templates/commands/type_loading.vt"));
        
        m_getCommands.put("browse", new BrowseCommand(injections));
        m_getCommands.put("browse-default-model", new BrowseDefaultModelCommand(injections));
        m_getCommands.put("focus", new FocusCommand(injections));
        m_getCommands.put("print", new PrintCommand(injections));
        m_getCommands.put("export", new ExportCommand(injections));

        m_postCommands.put("view", new ViewCommand(injections, "templates/views/object-property-list.vt"));
        m_postCommands.put("printView", new ViewCommand(injections, "templates/views/object-property-list-print.vt"));
        m_postCommands.put("view-referers", new ViewCommand(injections, "templates/components/referers.vt"));
        m_postCommands.put("changeModel", new ChangeModelCommand(injections,m_corpus,m_dataset,m_profile, "templates/commands/start.vt"));
        m_postCommands.put("selectComuni", new SetDatasetCommand(injections,"templates/components/graphs-list.vt"));
        m_postCommands.put("getSource", new GetSourceCommand(injections));
        // TODO(SM): this was done so that we can stop gracefull in those cases
        //           where the process get shut down without the JVM being signalled
        //           (for example, when running inside eclipse). But it's
        //           commented out because it's a potential security concern.
        //           In the future, we should make this configurable.
        //m_getCommands.put("stop", new StopCommand());
    }

    protected void createCommands(String id) {
        InjectionManager injections = createInjectionManager();
        m_getCommands.put("loginbasic", new LoginBasicCommand(injections,"templates/commands/login.vt"));
        m_getCommands.put("loginwebid", new LoginWebidCommand(injections,"templates/commands/home.vt"));
        m_getCommands.put("loginbasicAdministrator", new LoginBasicAdministrationCommand(injections,"templates/commands/loginAdministrator.vt"));
        m_getCommands.put("administration", new AdministrationCommand(injections,"templates/commands/administration.vt"));
        m_getCommands.put("administration_users", new AdministrationUsersCommand(injections,"templates/commands/administration_users.vt"));
        m_getCommands.put("administration_accesses", new AdministrationAccessesCommand(injections,"templates/commands/administration_accesses.vt"));
        m_getCommands.put("administration_datasets", new AdministrationDatasetsCommand(injections,"templates/commands/administration_datasets.vt"));
        m_getCommands.put("home", new HomePageCommand(injections,"templates/commands/home.vt"));
      
        m_getCommands.put("user_registration_basic", new UserRegistrationBasicCommand(injections,"templates/commands/user_registration_basic.vt"));
        m_getCommands.put("user_registration", new UserRegistrationCommand(injections,"templates/commands/user_registration.vt"));
        m_getCommands.put("user_registration_webid", new UserRegistrationWebidCommand(injections,"templates/commands/user_registration_webid.vt"));
        
        m_getCommands.put("save_user_basic", new SaveUserBasicCommand(injections,"templates/commands/save_user_basic.vt")); 
        m_postCommands.put("save_user_basic", new SaveUserBasicCommand(injections,"templates/commands/save_user_basic.vt"));
        m_getCommands.put("save_user_webid", new SaveUserWebidCommand(injections,"templates/commands/save_user_webid.vt"));        

        m_getCommands.put("logout", new LogoutCommand(injections));
        m_getCommands.put("start", new StartCommand(injections,filesComuni, "templates/commands/start.vt"));
        m_getCommands.put("selectDataset", new SelectDatasetCommand(injections,filesComuni, "templates/components/dataset-list.vt"));
        m_getCommands.put("selectDatasetForAdministration", new SelectDatasetAdministrationCommand(injections,filesComuni, "templates/components/dataset-list-administration.vt"));
        m_getCommands.put("selectGrafi", new SelectGraphsCommand(injections,"templates/components/graphs-list.vt"));
        m_getCommands.put("selectLoadingType", new SelectLoadingTypeCommand(injections,"templates/commands/type_loading.vt"));
        
        
        m_getCommands.put("changeModel", new ChangeModelCommand(injections,m_corpus,m_dataset,LongwellServer.getServer().getProfile(id), "templates/commands/start.vt"));
        m_getCommands.put("enableUsers", new EnableUsersCommand(injections));
        m_getCommands.put("fromUsersToPending", new DisableUsersCommand(injections));
        m_getCommands.put("fromUsersToAdministrator", new EnableUsersToAdminCommand(injections));   
        m_getCommands.put("disableAdmin", new DisableAdminCommand(injections));
        m_getCommands.put("create_certificate", new CreateCertificateCommand(injections,"templates/commands/create_certificate.vt"));
        m_getCommands.put("save_certificate", new SaveCertificateCommand(injections,"templates/commands/create_certificate.vt"));
        
        m_getCommands.put("load_server_certificate", new LoadServerCertificateCommand(injections));

        m_getCommands.put("browse", new BrowseCommand(injections));
        m_getCommands.put("browse-default-model", new BrowseDefaultModelCommand(injections));
        m_getCommands.put("focus", new FocusCommand(injections));
        m_getCommands.put("print", new PrintCommand(injections));
        m_getCommands.put("export", new ExportCommand(injections));
        m_getCommands.put("questions_list", new QuestionsListCommand(injections,"templates/commands/questions-list.vt"));
        m_getCommands.put("domanda", new DomandeCompetenzaCommand(injections));
        m_postCommands.put("view", new ViewCommand(injections, "templates/views/object-property-list.vt"));
        m_postCommands.put("printView", new ViewCommand(injections, "templates/views/object-property-list-print.vt"));
        m_postCommands.put("view-referers", new ViewCommand(injections, "templates/components/referers.vt"));
        m_postCommands.put("getSource", new GetSourceCommand(injections));
        m_postCommands.put("changeModel", new ChangeModelCommand(injections,m_corpus,m_dataset,LongwellServer.getServer().getProfile(id), "templates/commands/start.vt"));
        m_postCommands.put("setDataset", new SetDatasetCommand(injections,"templates/components/graphs-list.vt"));
        m_postCommands.put("graphsListAdministration", new GraphsListAdministrationCommand(injections,"templates/components/graphs-list-administration.vt"));
        
        m_postCommands.put("export", new ExportCommand(injections));
        m_postCommands.put("logout", new LogoutCommand(injections));
        // TODO(SM): this was done so that we can stop gracefull in those cases
        //           where the process get shut down without the JVM being signalled
        //           (for example, when running inside eclipse). But it's
        //           commented out because it's a potential security concern.
        //           In the future, we should make this configurable.
        //m_getCommands.put("stop", new StopCommand());
    }    
    protected InjectionManager createInjectionManager() {
        InjectionManager injections = new InjectionManager();

        injections.put("common-stylesheets", "templates/components/common-stylesheets.vt");
        injections.put("common-scripts", "templates/components/common-scripts.vt");
        injections.put("browse-stylesheets", "templates/components/browse-stylesheets.vt");
        injections.put("browse-scripts", "templates/components/browse-scripts.vt");
        injections.put("start-stylesheets", "templates/components/start-stylesheets.vt");
        injections.put("start-scripts", "templates/components/start-scripts.vt");
        injections.put("focus-stylesheets", "templates/components/focus-stylesheets.vt");
        injections.put("focus-scripts", "templates/components/focus-scripts.vt");

        injections.put("print-stylesheets", "templates/components/print-stylesheets.vt");
        
        injections.put("page-title", "templates/components/page-title.vt");
        injections.put("header-slide", "templates/components/header-slide.vt");
        injections.put("item-count", "templates/components/item-count.vt");

        injections.put("item-view", "templates/views/object-property-list.vt");
        injections.put("value-view", "templates/views/value.vt");
        injections.put("graph-list", "templates/components/graphs-list.vt");
        injections.put("dataset-list", "templates/components/dataset-list.vt");
        injections.put("views-pane", "templates/panes/views-pane.vt");
        injections.put("map-results-pane", "templates/panes/map-results-pane.vt");
        injections.put("export-gmap-results", "templates/export/gmap-results.vt");
        injections.put("timeline-results-pane", "templates/panes/timeline-results-pane.vt");
        
        
        return injections;
    }

    protected FlairMessage makeMessage(
            HttpServletRequest request,
            HttpServletResponse response
        ) {
        String profileID = request.getSession().getId();
        s_logger.info("Loading profile with id: "+sessionId);
    	String extraPath = request.getPathInfo();
        if (extraPath.length() > 0) {
            String s = URLDecoder.decode(
                extraPath.substring(extraPath.startsWith("/") ? 1 : 0));

            if (s.length() > 0) {
                profileID = s;
            }
        }

        Query query = new Query(request.getQueryString());
        //return new FlairMessage(this, request, response, m_ve, profileID, query, "");
        return new FlairMessage(this, request, response, m_ve, request.getSession().getId(), query, language);
    }

    protected void serveResource(
        HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        String pathInContext =
            request.getPathInfo().substring("/resources".length());

        Resource resource = m_resourceCache.getResource(pathInContext);
        if (resource != null && resource.exists()) {
            ResourceCache.ResourceMetaData metaData =
                (ResourceCache.ResourceMetaData)resource.getAssociate();

            response.setContentType(metaData.getMimeType());
            resource.writeTo(response.getOutputStream(), 0, resource.length());
        }
    }
    
    public static String getAssemblerDirectory(){
    	return m_TDBAssembler.toString();
    }
    
    

   
    private void configureServer(final String id) throws ServletException{
        /*Main config*/
        /*
         * Read configuration property files
         */
    	Properties basicPropertiesFile = new Properties();
       
        try {
            m_context = getServletContext();
            
            
            //load the path where is store the properties path
            File propertiesFile = new File(m_context.getRealPath("/")+"WEB-INF/conf/longwell.properties");
            s_logger.info("Reading properties file " + propertiesFile.getCanonicalPath());
            FileInputStream fis = new FileInputStream(propertiesFile);
            basicPropertiesFile.load(fis);
            fis.close();
        } catch (Exception e) {
            s_logger.error("Failed to read properties file", e);
            System.exit(1);
        }
        
        
        //load the file that contains all the configurations
        Properties properties = new Properties();
        File confFile = new File(basicPropertiesFile.getProperty("configure.path"));
        try {
			FileInputStream fisConf = new FileInputStream(confFile);
			properties.load(fisConf);
			fisConf.close();
		} catch (Exception e) {
            s_logger.error("Failed to read properties file", e);
            System.exit(1);
		}
			
	
        /*
         * Set defaults
         */
        
        	
    	language = properties.getProperty("defaults.locale.language");
    	String country = properties.getProperty("defaults.locale.country");

    	//Locale for property labels
    	String variant = properties.getProperty("defaults.locale.variant");
    	if (language != null) {
    		if (country != null) {
    			if (variant != null) {
    				Locale.setDefault(new Locale(language, country, variant));
    			} else {
    				Locale.setDefault(new Locale(language, country));
    			}
    		} else {
    			Locale.setDefault(new Locale(language));
    		}
    	}
    	
    	String timeZone = properties.getProperty("defaults.timeZone");
    	if (timeZone != null) {
    		TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
    	}
        //Locale for interface
        HashMap<String,String> languages = new HashMap<String, String>();
        languages.put(language, m_context.getRealPath("/")+"WEB-INF/resources/message_"+language+".properties");
        Localize localize = new Localize(languages);
        localize.setLocale(language);
        languageBundle = localize.getProperties();
        

        
        /*
         * Create default corpus
         */

        synchronized (this) {
	        Properties properties2 = new Properties();
	        try {
	        	
	        	properties2.put("directory", properties.getProperty("defaultCorpus.dir"));
	        	properties2.put("database", properties.getProperty("defaultCorpus.database"));
	        	properties2.put("modelName", properties.getProperty("defaultCorpus.modelName"));
	        	//properties2.put("TDBAssembler",m_context.getRealPath("/")+"WEB-INF"+ properties.getProperty("TDBAssembler"));
	        	//properties2.put("TDBAssembler",m_context.getRealPath("/")+"WEB-INF"+ properties.getProperty("TDBAssembler"));
	        	//properties2.put("SDBAssembler",m_context.getRealPath("/")+"WEB-INF"+ properties.getProperty("SDBAssembler"));
	        	properties2.put("TDBAssembler",properties.getProperty("TDBAssembler"));
	        	properties2.put("SDBAssembler",properties.getProperty("SDBAssembler"));
	        	properties2.put("login",l);
	            corpus = Corpus.createCorpus(
	                "urn:edu.mit.simile:object:defaultCorpus",
	                properties.getProperty("defaultCorpus.connector"),
	                properties2);
	        } catch (Exception e) {
	            s_logger.error("Failed to create default corpus", e);
	            System.exit(1);
	        }
	       
	        m_TDBAssembler = new File(properties2.getProperty("TDBAssembler"));
	        
			String dir =properties2.getProperty("TDBAssembler");
			filesComuni = m_TDBAssembler.listFiles();
			Dataset dataTmp=null;
			m_dataset = new ArrayList<Dataset>();
			for (int i = 0; i < filesComuni.length; i++) {
				File file = filesComuni[i];
				String assemblerFile = file.getName() ;    
				dataTmp = TDBFactory.assembleDataset(dir+"/"+assemblerFile);
				m_dataset.add(dataTmp);
			}
	        
	        //m_dataset = TDBFactory.assembleDataset(m_TDBAssembler);	
	        /*
	         * Start up longwell server
	         */
	
			
			
	//		 {
	//         	
	//             protected Profile createProfile(String id, Corpus corpus, File structuredModelsDir) {
	//             	m_profile=new FlairLocalProfile(id, corpus, structuredModelsDir);
	//                 return m_profile;
	//             }
	//         };  
			
	        
			File corpusSystemDir = new File(properties.getProperty("defaultCorpus.systemDir"));
	        try {
	        	if(longwellServer==null){
	        		
	                longwellServer = new LongwellServer(
	                        corpus,corpusSystemDir,
	                        new File(properties.getProperty("commonSystemDir")));   
	                
	                m_profile = new FlairLocalProfile(id, corpus, corpusSystemDir,languageBundle);
	                longwellServer.addProfile(id, m_profile);
	        	}
	        	else{        		
	        		m_profile = new FlairLocalProfile(id, corpus, corpusSystemDir,languageBundle);
	        		longwellServer.addProfile(id, m_profile);
	        	}
	
	        } catch (Exception e) {
	            s_logger.error("Failed to create longwell server", e);
	            System.exit(1);
	        }
	        longwellServer.setMapKey(properties.getProperty("map.google.key"));
	        //longwellServer.setFresnelPath(m_context.getRealPath("/")+"WEB-INF/conf/fresnel.n3");
	        longwellServer.setFresnelPath(properties.getProperty("fresnel.data.file.path"));
	        longwellServer.setGraphsMappingPath(properties.getProperty("graphs.mapping.competences.questions.path"));
	        longwellServer.setApplicationName(properties.getProperty("server.contextPath"));
	        longwellServer.setVersion(basicPropertiesFile.getProperty("version"));
	        longwellServer.setRelease(basicPropertiesFile.getProperty("release"));
	        longwellServer.setHttpsPort(properties.getProperty("server.port.https"));
	        longwellServer.setServerURL(properties.getProperty("server.host"));
	        longwellServer.setServerCertificate(properties.getProperty("server.certificate"));
	        longwellServer.setProxyHost(properties.getProperty("http.proxyHost"));
	        longwellServer.setProxyPort(properties.getProperty("http.proxyPort"));
	        longwellServer.setUsersDatasetPath(properties.getProperty("users.dataset"));
	        longwellServer.setModelForAuthentication(properties.getProperty("users.dataset"));
	        longwellServer.setDefaultFacetsNumber(Integer.parseInt(properties.getProperty("default.facets.number")));
	        longwellServer.setMaxValueForFacet(Integer.parseInt(properties.getProperty("max.value.for.each.facet")));
	        longwellServer.setCoordinateOnt(properties.getProperty("coordinate.ont"));
	        longwellServer.setUseMap(properties.getProperty("google.map"));
	        longwellServer.setGeocodingFile(properties.getProperty("geocoding"));
	        m_corpus = corpus;
	        
	        // end main config
        }
        //Load the data from file if the property is setted
        if(properties.getProperty("defaultCorpus.connector").equals("edu.mit.simile.longwell.corpus.MemoryConnector")){
        	s_logger.info("Loading data from " + properties.getProperty("dataDir"));
        	try {
        			String path =m_context.getRealPath("/")+"WEB-INF"+ properties.getProperty("dataDir");
        			File file = new File(path);
	        		LongwellServer.getServer().getProfile(sessionId).addData(file);
        	} catch (Exception e) {
        		s_logger.warn("Failed to import initialization data", e);
        	}       	
        }        
        File flairDir = new File(m_context.getRealPath("/")+"WEB-INF"+properties.getProperty("server.resourcePath", "ui/html"));
        try {
            File clientSideDir = new File(flairDir, "client-side");

            m_resourceCache = new ResourceCache();
            m_resourceCache.setResourceBase(clientSideDir.getCanonicalPath());
            m_resourceCache.start();
        } catch (Exception e) {
            s_logger.error("Failed to start resource cache", e);
            throw new ServletException("Failed to start resource cache", e);
        }

        try {       	
            m_ve = new VelocityEngine();
            m_ve.init(createInitProperties(flairDir));        		
        	createCommands(id);
        } catch (Exception e) {
            s_logger.error("Failed to initialize Velocity engine", e);
            throw new ServletException("Failed to initialize Velocity engine", e);
        }
        m_properties = properties;

    }
    
    public ServletContext getContext(){
    	return m_context; 
    }  
    protected void render(HttpServletRequest request, HttpServletResponse response, Renderer renderer) {

        double scale = Utilities.parseDouble(request.getParameter("s"), 1);
        long pixelX = Utilities.parseLong(request.getParameter("x"), 0);
        long pixelY = Utilities.parseLong(request.getParameter("y"), 0);
        long pixelWidth = Utilities.parseLong(request.getParameter("w"), 100);
        long pixelHeight = Utilities.parseLong(request.getParameter("h"), 100);
        
        double realX = pixelX / scale;
        double realY = pixelY / scale;
        double realWidth = pixelWidth / scale;
        double realHeight = pixelHeight / scale;
        
        Rectangle2D crop = new Rectangle2D.Double(realX, realY, realWidth, realHeight);
        BufferedImage image = new BufferedImage((int) pixelWidth, (int) pixelHeight, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2d = (Graphics2D) image.getGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        response.setContentType("image/png");

        try {
            g2d.scale(scale, scale);
            g2d.translate(-realX, -realY);
            renderer.render(g2d, crop, request);
            ImageIO.write(image, "png", response.getOutputStream());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            g2d.dispose();
            image.flush();
        }
    }
    
}
